package com.gitee.ywj1352.ds;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;

/**
 * Created by wenjie.yang on 2019/7/23.
 */
@SpringBootApplication
@EnableDiscoveryClient
@EnableScheduling
@RestController
@EnableHystrix
public class DSserverApplication {

    @Value("${spring.application.name}")
    private String  currentServiceName;

    @Autowired
    private DiscoveryClient discoveryClient;

    private Set<String> urls = new HashSet<>();

    public static void main(String[] args) {
        SpringApplication.run(DSserverApplication.class,args);
    }


    @Scheduled(fixedRate = 6*1000)
    public Object hi(){
        Set<String> urlsS = new HashSet<>(urls);
        List<ServiceInstance> instances = discoveryClient.getInstances(currentServiceName);
        instances.forEach(s->{
            urlsS.add(s.getHost()+":"+s.getPort()+"/");
        });
        urls.clear();
        urls = urlsS;
        return urls;
    }

    @GetMapping("/hi")
    @HystrixCommand(fallbackMethod = "findByIdFallback", commandProperties =
        @HystrixProperty(name = "execution.isolation.strategy", value = "SEMAPHORE")
    )
    public Object getInstance(){
        return urls;
    }


    @GetMapping("/rest-api/hello-world")
    public Object helloWorld() throws Exception{

        System.out.println("hello-world");
        Random random = new Random();
        int i = random.nextInt(100);
        Thread.sleep((long)i);
        return "hello-world";
    }



    @GetMapping("/foo/{segment}")
    public Object foo(@PathVariable("segment") String segment) throws Exception{

        System.out.println("hello-world");
        Random random = new Random();
        int i = random.nextInt(100);
        Thread.sleep((long)i);
        return "hello-world" + segment;
    }

}
